package com.ywjh.inter.service;

import com.ywjh.inter.common.MemKey;
import com.ywjh.inter.common.SystemConfig;
import com.ywjh.inter.conn.MemcacheConn;

import io.agora.media.RtcTokenBuilder;
import io.agora.media.RtcTokenBuilder.Role;

public class RtcService {
	private static RtcService instance;

	public static RtcService getInstance() {
		if (instance == null) {
			instance = new RtcService();
		}
		return instance;
	}

	private long expirationTimeInSeconds = 3600;

	public String token(String channelName, String userAccount) {

		String token = MemcacheConn.getInstance().get(MemKey.RTC_TOKEN_ + channelName + "_" + userAccount);
		if (token != null) {
			return token;
		} else {
			RtcTokenBuilder tokenBuilder = new RtcTokenBuilder();
			int timestamp = (int) (System.currentTimeMillis() / 1000 + expirationTimeInSeconds);
//			token = tokenBuilder.buildTokenWithUserAccount(SystemConfig.RTC_appId, SystemConfig.RTC_appCertificate,
//					channelName, userAccount, Role.Role_Publisher, timestamp);//3.8以前的
			token = tokenBuilder.buildTokenWithUid(SystemConfig.RTC_appId, SystemConfig.RTC_appCertificate, channelName,
					uid(userAccount), Role.Role_Publisher, timestamp);//3.8以后
			MemcacheConn.getInstance().put(MemKey.RTC_TOKEN_ + channelName + "_" + userAccount, token,
					expirationTimeInSeconds);
			System.out.println("memcache k=" + MemKey.RTC_TOKEN_ + channelName + "_" + userAccount + " v=" + token);
		}
		return token;
	}
	
	

	private int uid(String userAccount) {//user_33
		int uid = -1;
		try {
			uid = Integer.parseInt(userAccount.replaceAll("user_", ""));
		} catch (Exception e) {
			e.printStackTrace();
		}
		//return uid;
		return 0;
	}
}
